package leo.peersim.paxos;

import java.util.LinkedList;


import org.apache.log4j.Logger;

import peersim.config.Configuration;
import peersim.core.CommonState;
import peersim.core.Control;
import peersim.core.Network;
import peersim.core.Node;
import peersim.edsim.EDSimulator;

public class RequestTrigger implements Control {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	private final int protocolID;
	
	private LinkedList<String> messageQueue = null;
	private LinkedList<Integer> clients = null;
	
	public RequestTrigger(String prefix) {
		this.protocolID = Configuration.getPid(prefix + "." + "protocol");
		
		this.messageQueue = new LinkedList<String>();
		this.messageQueue.offer("A");
		this.messageQueue.offer("B");
		this.messageQueue.offer("C");
		//this.messageQueue.offer("D");
		
		this.clients = new LinkedList<Integer>();
		this.clients.offer(new Integer(0));
		this.clients.offer(new Integer(1));
		this.clients.offer(new Integer(1));
		
	}

	/**
	 * 
	 * 
	 */
	@Override
	public boolean execute() {
		String command = this.messageQueue.poll();
		
		if (command==null) {
			return false;
		}
		
		//int randomInt = CommonState.r.nextInt( Network.size() );
		int randomInt = 0; // fixed leader
		//int randomInt = this.clients.poll().intValue(); 
		Node randomLeader = Network.get(randomInt);
		
		logger.debug(CommonState.getTime() + "\ttriggering request _" + command + "_ to agent[" + randomLeader.getID() + "]...");
		
		ClientRequest request = new ClientRequest(command);
		
		EDSimulator.add(0, request, randomLeader, this.protocolID);
		
		return false;
	}
	
	

}


